# coding=UTF-8

import cgi
import wsgiref.handlers

import sys,os
from model.greeting import Greeting
from model.article import Article
from model.comment import Comment
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
import util



class MainPage(webapp.RequestHandler):
  def get(self):
    greetings_query = Greeting.all().order('-date')
    greetings = greetings_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = '退出登录'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = '登录'

    template_values = {
      'greetings': greetings,
      'url': url,
      'url_linktext': url_linktext,
      'dirs':sys.path,
      }
    util.render('view/guestbook.html',template_values,self)

class Guestbook(webapp.RequestHandler):
  def post(self):
    greeting = Greeting()
    if users.get_current_user():
      greeting.author = users.get_current_user()
    greeting.content = cgi.escape(self.request.get('content')).rstrip()[0:8000]
    greeting.put()
    self.redirect('/guestbook/')
    
def main():
  application = webapp.WSGIApplication(
                                       [('/guestbook/', MainPage),
                                        ('/guestbook/sign', Guestbook)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
